package com.happy_hao.topbiz.config;

import com.happy_hao.topbiz.realm.EmailCodeRealm;
import com.happy_hao.topbiz.realm.FormRealm;
import com.happy_hao.topbiz.realm.Oauth2Realm;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    @Bean
    public FormRealm getFormRealm() {
        return new FormRealm();
    }

    @Bean
    public EmailCodeRealm getEmailCodeRealm() {
        return new EmailCodeRealm();
    }

    @Bean
    public Oauth2Realm getOauth2Realm() {
        return new Oauth2Realm();
    }

    @Bean
    public ModularRealmAuthenticator authenticator() {
        ModularRealmAuthenticator authenticator = new ModularRealmAuthenticator();
        authenticator.setAuthenticationStrategy(new CustomAuthenticationStrategy());
        return authenticator;
    }

    @Bean
    public SessionManager sessionManager() {
        DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
        // 设置会话超时时间（毫秒） - 30分钟
        sessionManager.setGlobalSessionTimeout(1800000L);
        // 设置会话验证间隔
        sessionManager.setSessionValidationInterval(1800000L);
        // 启用会话验证
        sessionManager.setSessionValidationSchedulerEnabled(true);
        return sessionManager;
    }


    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setSessionManager(sessionManager());
        securityManager.setAuthenticator(authenticator());
        Collection<Realm> realms = new ArrayList<>();
        realms.add(getFormRealm());
        realms.add(getEmailCodeRealm());
        realms.add(getOauth2Realm());
        securityManager.setRealms(realms);
        return securityManager;
    }

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean() {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        bean.setSecurityManager(getDefaultWebSecurityManager());
        Map<String, String> filterMap = new LinkedHashMap<>();

        // 1. 公共资源（无需认证）
        filterMap.put("/topbiz/anon/**", "anon");

        // 2. 需要角色的路径
        filterMap.put("/topbiz/user/**", "roles[user]");
        filterMap.put("/topbiz/administrator/**", "roles[admin]");
        filterMap.put("/topbiz/msg/**", "roles[msg]");

        // 3. 其他所有路径
        filterMap.put("/**", "authc");
        bean.setFilterChainDefinitionMap(filterMap);
        return bean;
    }
}
